package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.entity.EnrollSchool;
import com.xmy.cultivate.entity.EnrollSchoolMember;
import com.xmy.cultivate.entity.Organization;
import com.xmy.cultivate.entity.Staff;
import com.xmy.cultivate.service.IEnrollSchoolMemberService;
import com.xmy.cultivate.service.IEnrollSchoolService;
import com.xmy.cultivate.service.IOrganizationService;
import com.xmy.cultivate.service.IStaffService;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.PageResult;
import com.xmy.cultivate.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

//校区管理
@RestController
@RequestMapping("/api/enrollSchool")
@Scope("prototype")
public class EnrollSchoolController extends BaseController {

    @Autowired
    IEnrollSchoolService enrollSchoolService;

    @Autowired
    @Lazy
    IOrganizationService iOrganizationService;

    @Autowired
    IStaffService iStaffService;

    @Autowired
    private IEnrollSchoolMemberService enrollSchoolMemberService;

    @GetMapping()
    public Result enrollSchoolList(@RequestParam Map<String, Object> reMap){
        int pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? -1 : Integer.parseInt((String) reMap.get("pageNum"));
        int pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? -1 : Integer.parseInt((String) reMap.get("pageSize"));
        Page<EnrollSchool> iPage = new Page<>(pageNum, pageSize);

        QueryWrapper<EnrollSchool> enrollSchoolQueryWrapper = new QueryWrapper<>();
        enrollSchoolQueryWrapper.select("*,(SELECT name FROM organization WHERE id = enroll_school.school_id LIMIT 1) AS schoolName");
        enrollSchoolQueryWrapper.eq("pid", 0);
        enrollSchoolService.page(iPage, enrollSchoolQueryWrapper);
        return new Result(Code.OK, new PageResult<>(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));

    }

    //修改和切换时的列表
    @GetMapping("getSchoolIdList")
    public Result getSchoolIdList(){
        QueryWrapper<EnrollSchool> enrollSchoolQueryWrapper = new QueryWrapper<>();
        enrollSchoolQueryWrapper.select("*,(SELECT name FROM organization WHERE id = enroll_school.school_id LIMIT 1) AS schoolName");
        enrollSchoolQueryWrapper.eq("pid", 0);
        List<EnrollSchool> list = enrollSchoolService.list(enrollSchoolQueryWrapper);
        return new Result(Code.OK, list);

    }

    @PostMapping()
    public Result addEnrollSchool(@RequestBody EnrollSchool enrollSchool){
        if (enrollSchool.getSchoolId() != null && enrollSchool.getSchoolId() > 0) {
            Organization organizationServiceById = iOrganizationService.getById(enrollSchool.getSchoolId());
            if (organizationServiceById != null) {
                enrollSchool.setSchoolName(organizationServiceById.getName());
            }
        }
        boolean save = enrollSchoolService.save(enrollSchool);
        if (!save) {
            return new Result(Code.ERROR,"","添加失败");
        }
        return new Result(Code.OK);
    }

    @PutMapping()
    public Result updateEnrollSchool(@RequestBody EnrollSchool enrollSchool){
        if (enrollSchool.getSchoolId() != null && enrollSchool.getSchoolId() > 0) {
            Organization organizationServiceById = iOrganizationService.getById(enrollSchool.getSchoolId());
            if (organizationServiceById != null) {
                enrollSchool.setSchoolName(organizationServiceById.getName());
            }
        }
        boolean b = enrollSchoolService.updateById(enrollSchool);
        if (!b) {
            return new Result(Code.ERROR,"","修改失败");
        }
        return new Result(Code.OK);
    }

    @DeleteMapping()
    public Result deleteEnrollSchool(@RequestBody EnrollSchool enrollSchool){
        long count = enrollSchoolMemberService.count(new QueryWrapper<EnrollSchoolMember>().eq("enroll_school_id", enrollSchool.getId()).eq("status", 1));
        if (count > 0) {
            return new Result(Code.ERROR,"","先删除教师，在回来删除校区");
        }
        enrollSchoolService.removeById(enrollSchool.getId());
        return new Result(Code.OK);
    }

    //筛选->教师列表
    @GetMapping("checkTeacher")
    public Result checkTeacher(@RequestParam Map reMap,@RequestParam(value = "schoolIdList",defaultValue = "") String[] schoolIdList){
        Integer pageNum = StringUtils.isEmpty((String)reMap.get("pageNum")) ? 1 : Integer.valueOf((String)reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String)reMap.get("pageSize")) ? 1000: Integer.valueOf((String)reMap.get("pageSize"));

        IPage<Staff> page = new Page<>(pageNum,pageSize);

//        String teamId = (String) reMap.get("teamId");

        QueryWrapper<Staff> staffQueryWrapper =  new QueryWrapper<>();

        String name = (String) reMap.get("name");
        if(StringUtils.isNotBlank(name)){
            staffQueryWrapper.like("name",name);
        }

        if(schoolIdList.length > 0){
            String schoolIdStr = String.join(",", schoolIdList);
            staffQueryWrapper.and(i->i.eq("scope_class_mode",1).or().inSql("id","select for_id from appoint_school where type=2 and school_id in("+schoolIdStr+")"));
        }else {
            //System.out.print("baseSchoolIdStr:"+baseSchoolIdStr);
            staffQueryWrapper.and(i->i.eq("scope_class_mode",1).or().inSql("id","select for_id from appoint_school where type=2 and school_id in("+this.baseSchoolIdStr+")"));
        }

//        if(StringUtils.isNotBlank(teamId)){
            staffQueryWrapper.notInSql("id","select teacher_id from enroll_school_member where status = 1 and deleted=0");
//        }
        //staffQueryWrapper.eq(StringUtils.isNotBlank(schoolId),"school_id",schoolId);

        iStaffService.findAll(page,staffQueryWrapper);

        return new Result(Code.OK,new PageResult<>(page.getRecords(),page.getTotal(),page.getPages()));
    }
}
